



package com.sakila.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.sakila.dbo.CityDBO;
import com.sakila.util.DBConnection;


public class CityDAO implements ICityDAO {





	  private Logger logger = Logger.getLogger(this.getClass());
	//SimpleDateFormat formatter = new SimpleDateFormat(
		//	"yyyy.MM.dd G 'at' HH:mm:ss z");

	/* (non-Javadoc)
	 * @see com.sakila.dao.ICityDAO#findById(int)
	 */
	@Override
	public CityDBO findById(int cityId) {
		CityDBO dbo = null;
		ResultSet rs = null;
		PreparedStatement statement = null;
		Connection connection = null;
		try {
			connection = DBConnection.getConnection();
			StringBuilder sb = new StringBuilder();
			sb.append("select city_id as cityId, city as city, country_id as countryId, last_update as lastUpdate");
			sb.append("from city ");
			sb.append("where city_id = " + cityId);
			statement = connection.prepareStatement(sb.toString());
			logger.info("Executing Query Here in City DAO: "+ sb.toString());
			rs = statement.executeQuery();
			if (rs.next()) {
				dbo = new CityDBO();
				dbo.setCity_id(rs.getInt("cityId"));
				dbo.setCity(rs.getString("city"));
				dbo.setCountry_id(rs.getInt("countryId"));
				dbo.setLast_update(rs.getDate("lastUpdate"));
				
				
			}

		} catch (SQLException e) {
			logger.error("Exception in City DAO" + e );
			throw new RuntimeException(e);
		} finally {
			DBConnection.close(rs, statement, connection);
		}
		return dbo;
	}

	/* (non-Javadoc)
	 * @see com.sakila.dao.ICityDAO#findAll()
	 */
	@Override
	public List<CityDBO> findAll() {
		List<CityDBO> returnList = null;
		ResultSet rs = null;
		PreparedStatement statement = null;
		Connection connection = null;
		CityDBO dbo = null;
		try {
			connection = DBConnection.getConnection();
			StringBuilder sb = new StringBuilder();
			sb.append("select city_id as cityId, city as city, country_id as countryId, last_update as lastUpdate");
			sb.append("from city ");
			statement = connection.prepareStatement(sb.toString());
			logger.info("Executing Query Here City DAO infindAll: "+ sb.toString());
			rs = statement.executeQuery();
			returnList = new ArrayList<CityDBO>();
			while (rs.next()) {
				dbo = new CityDBO();
				dbo.setCity_id(rs.getInt("cityId"));
				dbo.setCity(rs.getString("city"));
				dbo.setCountry_id(rs.getInt("countryId"));
				dbo.setLast_update(rs.getDate("lastUpdate"));
				returnList.add(dbo);
				
			}

		} catch (SQLException e) {
			logger.error("Exception in City DAO" + e );
			throw new RuntimeException(e);
		} finally {
			DBConnection.close(rs, statement, connection);
		}
logger.debug("Display Me everyone from List:" + returnList);
		return returnList;
	}
	
}

